package com.boco.pciv.service.sys.impl;

import cn.hutool.core.util.StrUtil;
import com.boco.pciv.SysProperties;
import com.boco.pciv.core.entity.PageResultBase;
import com.boco.pciv.core.entity.SearchCriteria;
import com.boco.pciv.core.exception.PcivException;
import com.boco.pciv.core.service.PcivBaseServiceImpl;
import com.boco.pciv.core.util.SearchUtil;
import com.boco.pciv.entity.sys.RoleBasicInfo;
import com.boco.pciv.entity.sys.UserInfo;
import com.boco.pciv.mapper.sys.IRoleMapper;
import com.boco.pciv.mapper.sys.IUserMapper;
import com.boco.pciv.service.shiro.ShiroUtils;
import com.boco.pciv.service.sys.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl extends PcivBaseServiceImpl<IUserMapper,UserInfo,Integer> implements IUserService {
	Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private IRoleMapper rolemapper;
    @Autowired
    SysProperties sysConfig;
    @Autowired
    IUserService self;

    @Override
	public PageResultBase getPage(SearchCriteria param) {
		List<UserInfo> list= mapper.queryList(param.getQueryMap());
        for (UserInfo info :list){
            info.setRoles( rolemapper.queryByUser(info.getUserId()));
        }
		return SearchUtil.parse(list);
	}

    @Override

	public UserInfo getOneByUserId(String userId) {
		UserInfo data = mapper.queryOneByUserId(userId);
        if (data!=null) {
            data.setRoles(rolemapper.queryByUser(userId));
            List<String> rids = new ArrayList<>();
            for (RoleBasicInfo info : data.getRoles()) {
                rids.add(info.getRoleId());
            }
            String[] array=rids.toArray(new String[rids.size()]);
            data.setRoleIds(array);
        }
		return data;
	}
    @Override
	public void add(UserInfo user) {
        if (user==null){
            throw  new PcivException("新增用户数据不能为空");
        }
        UserInfo info = mapper.queryOneByUserId(user.getUserId());
        if (info!=null){
            throw new PcivException("该账号已经存在");
        }
        if(StrUtil.isBlank(user.getPassword())){
            user.setPassword(sysConfig.getDefaultPassword());
        }
        user.setState(1);
		user.setPassword(ShiroUtils.encryptPassword(user.getUserId(),user.getPassword()));
		mapper.insert(user);
        InsertRoleRe(user.getUserId(),user.getRoleIds());
	}
	
    @Override
    public void addOther(UserInfo user) {
        if (user==null){
            throw  new PcivException("新增用户数据不能为空");
        }
        UserInfo info = mapper.queryOneByUser(user);
        if (info!=null){
            throw new PcivException("该账号已经存在");
        }
        if(StrUtil.isBlank(user.getPassword())){
            user.setPassword(sysConfig.getDefaultPassword());
        }
        user.setState(1);
        user.setPassword(ShiroUtils.encryptPassword(user.getUserId(),user.getPassword()));
        mapper.insert(user);
        InsertRoleRe(user.getUserId(),user.getRoleIds());
    }
    @Override
	public void deleteByUserId(String userId){
		mapper.deleteByUserId(userId);
	}

    @Override
    public String getUserNameByUserId(String userId) {
        UserInfo one = self.getOneByUserId(userId);
        return one==null?"":one.getUserName();
    }

    @Override
    public void unDelete(String userId) {
        UserInfo user = new UserInfo();
        user.setUserId(userId);
        user.setState(1);
        mapper.updateStatus(user);
    }

    @Override
	public Integer edit(UserInfo user) {
        Integer rtn = mapper.update(user);
        //删除角色用户对应关系
        mapper.deleteUserRoleByUserId(user.getUserId());
        InsertRoleRe(user.getUserId(),user.getRoleIds());
        return rtn;
	}

	public void deleteUserRoleByUserId(String userId){
	    mapper.deleteUserRoleByUserId(userId);
    }

	private void InsertRoleRe(String userId,String[] roleIds){
	    if (roleIds==null)
	        return;
        for (String roleid :roleIds){
            Map<String,String> reMap = new HashMap<String, String>();
            reMap.put("userId",userId);
            reMap.put("roleId",roleid);
            mapper.insertUserRole(reMap);
        }
    }
    
    @Override
    public void insertUserRole(Map<String, String> userReinfo){
        mapper.insertUserRole(userReinfo);
    }
	@Override
    public void lock(String userId) {
        UserInfo user = new UserInfo();
        user.setUserId(userId);
        user.setState(2);
		mapper.updateStatus(user);
	}

	@Override
	public void unLock(String userId) {
        UserInfo user = new UserInfo();
        user.setUserId(userId);
        user.setState(1);
        mapper.updateStatus(user);
	}

	@Override
	public void modifyPassword(String userid, String newPassword) {
		if(StrUtil.isBlank(newPassword))
			newPassword= sysConfig.getDefaultPassword();
        newPassword = ShiroUtils.encryptPassword(userid,newPassword);
        //SecureUtil.md5(newPassword);
        UserInfo user = new UserInfo();
        user.setUserId(userid);
        user.setPassword(newPassword);
        mapper.updatePassword(user);
	}

    @Override
    public boolean testLogin(String userId, String password) {
        UserInfo user = new UserInfo();
        user.setUserId(userId);
        user.setPassword(ShiroUtils.encryptPassword(userId,password));
        UserInfo userinfo = mapper.login(user);
        return userinfo != null;
    }

    @Override
	public UserInfo login(String userId, String password) {
		UserInfo user = new UserInfo();
		user.setUserId(userId);
		user.setPassword(ShiroUtils.encryptPassword(userId,password));
		return mapper.login(user);
	}

	@Override
	public void updateLoginTime(String userId) {
		mapper.updateLoginTime(userId);
	}
}
